package com.hy.admin.controller.pages;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hy.admin.domain.dto.AdminWebUserDto;
import com.hy.admin.entity.MemberEntity;
import com.hy.admin.entity.YangCoinEntity;
import com.hy.admin.helper.request.AccountRequest;
import com.hy.admin.security.service.business.SecurityCurrentUserLoader;
import com.hy.admin.security.utils.MyHttpclientUtils;
import com.hy.admin.service.AccountService;
import com.hy.admin.service.MemberService;
import com.hy.admin.service.YangCoinService;
import com.hy.config.ConfigurationUtils;
import com.hy.core.response.ServicesResult;
import com.hy.utils.CookieUtils;
import com.hy.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/page/weixin")
public class PageControllerWeiXin extends PageControllerBase{

	@Autowired
    private AccountService accountService;
	@Autowired
	private YangCoinService yangCoinService;

	@Value("${security.admin.Authorization}")
	private String headerAuthorization;

	@ResponseBody
	@RequestMapping(value="/authen", method=RequestMethod.POST)
	public ServicesResult<MemberEntity> authen(String userName, String password, HttpSession session) {
		ServicesResult<MemberEntity> result = new ServicesResult<MemberEntity>();
		boolean reLogin = true;
		if(isLogin(ROLE_WEIXIN)) {
			MemberEntity memberEntity = (MemberEntity)session.getAttribute("memberEntity");
			if(memberEntity!=null && memberEntity.getMobile().equals(userName)) {
				reLogin = false;
				result.setResult(memberEntity);
			}
		}
		if(reLogin) {
			if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)) return result;
			try {
				Map<String, String> param = new HashMap<>();
				param.put("grant_type", "password");
				param.put("username", userName);
				param.put("password", password);
				ObjectMapper objectMapper=new ObjectMapper();
				String s=request.getContextPath();
				String realPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
				String resp = MyHttpclientUtils.doPost(realPath+"/oauth/token",headerAuthorization, param);
				AdminWebUserDto adminWebUserDto=null;
				if (StringUtils.isNotBlank(resp)) {
					adminWebUserDto = objectMapper.readValue(resp, AdminWebUserDto.class);
					MemberEntity member=adminWebUserDto.getUser().getMemberEntity();
					member.setAccess_token(adminWebUserDto.getAccess_token());
					result.setResult(member);
					markedLogin(userName, ROLE_WEIXIN);
					session.setAttribute("memberEntity", member);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
//			AccountRequest accountRequest = new AccountRequest();
//			accountRequest.setMobile(userName);
//			accountRequest.setPassword(password);
//			result = accountService.login(accountRequest);
//			MemberEntity memberEntity = result.getResult();
//			if(memberEntity != null) {
//				markedLogin(memberEntity.getMobile(), ROLE_WEIXIN);
//				session.setAttribute("memberEntity", memberEntity);
//			}
		}
		return result;
	}

	@ResponseBody
	@RequestMapping(value="/autoLogin", method=RequestMethod.POST)
	public ServicesResult<MemberEntity> autoLogin(Long memberId, HttpSession session) {
		ServicesResult<MemberEntity> result = new ServicesResult<MemberEntity>();
		result = accountService.getMember(memberId);
		MemberEntity memberEntity = result.getResult();
		if(memberEntity != null) {
			markedLogin(memberEntity.getMobile(), ROLE_WEIXIN);
			session.setAttribute("memberEntity", memberEntity);
		}
		result.setResult(memberEntity);
		return result;
	}
	
	@RequestMapping(value={"", "/", "/login" }, method=RequestMethod.GET)
	public String toLogin(Model model, HttpServletRequest request, HttpSession session) {
		SecurityCurrentUserLoader securityCurrentUserLoader=new SecurityCurrentUserLoader();
		MemberEntity memberEntity=securityCurrentUserLoader.load();
		if(memberEntity!=null ) {
			// 获取请求是从哪里来的
			String referer = request.getHeader("referer");
			if(StringUtils.isNotBlank(referer)){
				System.out.println("referer:"+referer);
				referer = referer.replace("http://","");

				String platform = ConfigurationUtils.getString("project.environment");
				if("production".equals(platform)){
					referer = referer.replace("/admin","");
				}else if("test".equals(platform)){
					referer = referer.replace("/test","");
				}

				referer = referer.substring(referer.indexOf("/"), referer.length());
				return "redirect:"+referer;
			}
			return "redirect:/page/weixin/recharge";
		}
		saveDefaultAttributes2Model(model);
		
		return makeViewName("login");
	}

	@RequestMapping(value={"/remove" }, method=RequestMethod.GET)
	public void removeCookie(HttpServletResponse response) {
		CookieUtils.removeCookie(response,"openid");
	}
	
	@RequestMapping(value="/recharge", method=RequestMethod.GET)
	public String toRecharge(Model model, HttpServletRequest request, HttpSession session) {

		SecurityCurrentUserLoader securityCurrentUserLoader=new SecurityCurrentUserLoader();
		MemberEntity memberEntity=securityCurrentUserLoader.load();
		if(memberEntity==null) {
			return "redirect:/page/weixin/login";
		}

//		if(!isLogin(ROLE_WEIXIN)) {
//			return "redirect:/page/weixin/login";
//		}
		String openId = CookieUtils.getCookie(request,"openid");
		if(StringUtils.isBlank(openId)){
			System.out.println(request.getScheme()+"://"+ request.getServerName()+request.getContextPath());
			try {
				String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ ConfigurationUtils.getString("weixin_app_id")
                +"&redirect_uri="+ URLEncoder.encode(request.getScheme()+"://"+ request.getServerName()+request.getContextPath()+"/page/weixin/oauth", "utf-8")+"&response_type=code&scope=snsapi_base&state=pay#wechat_redirect";
				return "redirect:" + url;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		saveDefaultAttributes2Model(model);
		ServicesResult<List<YangCoinEntity>> result = yangCoinService.list();
		model.addAttribute("coinList", result.getResult());
//		MemberEntity memberEntity = (MemberEntity)session.getAttribute("memberEntity");
		model.addAttribute("member", memberEntity);

		return makeViewName("recharge");
	}

	@RequestMapping(value="/oauth", method=RequestMethod.GET)
	public String oauth(Model model,  HttpServletResponse response) {
		String code = request.getParameter("code");
		String from = request.getParameter("from");

		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ ConfigurationUtils.getString("weixin_app_id")
				+ "&secret="+ConfigurationUtils.getString("weixin_app_secret")
				+ "&code="+code
				+ "&grant_type=authorization_code";
		String result = HttpUtils.sendGet(url);
		System.out.println(result);
		JSONObject jsonObject = JSON.parseObject(result);
		String openid = jsonObject.getString("openid");
		System.out.println(openid);
		if(StringUtils.isNotBlank(openid)){
			CookieUtils.setCookie(response,"openid",openid, 3600*24*30);
		}
		saveDefaultAttributes2Model(model);
		if(StringUtils.isNotBlank(from)){
			if(from.equals("course")){
				return "redirect:/page/course/list";
			}else if(from.equals("question")){
				return "redirect:/page/course/question";
			}
		}
		return "redirect:/page/weixin/recharge";
	}

	@Override
	protected String getViewPrefix() {
		return "weixin/";
	}

}
